package cn.js.sangu.unitStore.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.js.sangu.unitStore.entity.ChatRecord;
import cn.js.sangu.unitStore.mapper.ChatRecordMapper;
import cn.js.sangu.unitStore.websocket.WebSocketService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ChatRecordService {

    @Autowired
    ChatRecordMapper chatRecordMapper;

    @Autowired
    WebSocketService webSocketService;

    public List<ChatRecord> getRecordByUser(String uid, String oppoId) {
        return chatRecordMapper.selectList(new QueryWrapper<ChatRecord>()
                .eq("user_id", uid)
                .eq("oppo_id", oppoId)
                .or()
                .eq("user_id", oppoId)
                .eq("oppo_id", uid)
                .orderByAsc("id"));
    }

    public void saveChatRecord(ChatRecord chatRecord) {
        // 确保内容不为null
        if (chatRecord.getContent() == null) {
            chatRecord.setContent("");
        }
        chatRecordMapper.insert(chatRecord);
    }

    public void cleanChatRecord(String uid, String oppoId) {
        QueryWrapper<ChatRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uid).eq("oppo_id", oppoId)
                .or().eq("user_id", oppoId).eq("oppo_id", uid);
        chatRecordMapper.delete(queryWrapper);
        log.info("用户 {} 与 {} 的聊天记录已清空", uid, oppoId);
    }

    /**
     * 更新消息已读状态
     * 
     * @param recordId 消息记录ID
     * @param read     是否已读
     */
    public void updateReadStatus(Long recordId, Integer read) {
        ChatRecord chatRecord = chatRecordMapper.selectById(recordId);
        if (chatRecord != null) {
            chatRecord.setIsRead(read);
            chatRecordMapper.updateById(chatRecord);
            log.info("消息 {} 已读状态更新为 {}", recordId, read);

            // 通过WebSocket给对方发送刷新提醒
            String oppoId = chatRecord.getOppoId();
            String userId = chatRecord.getUserId();

            // 确定消息接收方
            String receiverId = chatRecord.getUserId().equals(userId) ? userId : oppoId;
            webSocketService.sendRefreshNotification(receiverId, recordId);
        } else {
            log.warn("未找到消息记录: {}", recordId);
        }
    }
}
